package com.paas.demo.interceptor;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class AuthInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug(request.getRequestURI());
		}
		logger.info(request.getRequestURI());

		return super.preHandle(request, response, handler);
	}

	@SuppressWarnings("unused")
	private boolean write403(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> maps = new HashMap<String, Object>();
		maps.put("code", 11012);
		maps.put("msg", "用户无权操作");
		String result = JSON.toJSONString(maps);
		response.setStatus(403);
		response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(result);
		return false;
	}

	public boolean timeOut(HttpServletResponse response) throws IOException {
		Map<String, Object> maps = new HashMap<String, Object>();
		maps.put("code", 11011);
		maps.put("msg", "登录超时");
		String result = JSON.toJSONString(maps);
		response.setStatus(403);
		response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(result);
		return false;
	}

}
